<template>
  <view class="pop-product-choose-guige">
    <u-popup
      ref="popup_avatar_nick"
      :safeAreaInsetBottom="true"
      bgColor="#ffffff"
      :show="show_pop"
      mode="bottom"
      :closeOnClickOverlay="true"
      round="30"
      @close="handleClose"
      @open="handleOpen">
      <scroll-view class="choose-scroll" scroll-y="true">
        <view class="pop-ctx">
          <view class="info-modal-inner">
            <view class="modal-head">
              <view class="top-box">
                <view class="poster-box" @click="doPreviewPoster()">
                  <image :src="guige_poster" mode="aspectFill"></image>
                </view>
                <view class="info-box flex1">
                  <view class="title ellipsis-2">
                    {{ info.title }}
                  </view>

                  <view class="price-box flex">
                    <view class="price">
                      <text class="price-val" v-if="guige_select.inventoryId">
                        {{ guige_select.priceSale || "0.00" }}
                      </text>
                      <text class="price-val" v-else>
                        {{ info.priceSale || "0.00" }}
                      </text>
                    </view>
                  </view>
                </view>
                <view class="close-box flex-center" @click="doClose()">
                  <image
                    src="@/static/product-detail/close.png"
                    mode=""
                    class="modal-close"></image>
                </view>
              </view>
            </view>

            <view class="modal-ctx">
              <view class="guige-info">
                <view class="sec-guige">
                  <view
                    v-if="sku_mode == '无规格'"
                    class="sec-guige-dan"
                    data-type="无规格">
                    <view class="main-title">规格</view>
                    <view class="guige-list flex">
                      <view
                        class="guige-item fit-text"
                        v-for="(item, index) in guige_list"
                        :key="index"
                        @click="do_toggle_wuguige(item)"
                        :class="{
                          selected:
                            guige_select.inventoryId == item.inventoryId,
                          nokucun: !item.kucun,
                        }">
                        {{ item.keyVals || "默认" }}
                      </view>
                    </view>
                  </view>

                  <view v-else class="sku-wrap" data-type="多规格">
                    <view
                      class="sku-group"
                      v-for="(sku_group, group_index) in sku_sections"
                      :key="group_index">
                      <view class="main-title">
                        {{ sku_group.key }}
                      </view>
                      <view class="sku-list flex">
                        <view
                          class="sku-item fit-text"
                          v-for="(sku_item, item_index) in sku_group.child"
                          :key="item_index"
                          @click="
                            do_toggle_sku(
                              sku_item,
                              item_index,
                              sku_group,
                              group_index
                            )
                          "
                          :class="{
                            selected: sku_item.is_selected,
                            nokucun: !sku_item.is_allow_select,
                          }">
                          {{ sku_item.title }}
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
              </view>

              <view class="sec-num">
                <view class="main-title flex-between">
                  <view class="title-text">数量</view>
                  <!-- <view class="number-box flex">
										<view class="box-act box-minus" @click="doMinus()">
											<image src="@/static/product-detail/num-minus.png" mode=""></image>
										</view>
										<text class="num">{{buyNumber}}</text>
										<view class="box-act box-plus" @click="doPlus()">
											<image src="@/static/product-detail/num-plus.png" mode=""></image>
										</view>
									</view> -->

                  <view class="act-box">
                    <u-number-box
                      v-model="buyNumber"
                      :step="1"
                      :min="1"
                      :max="max_buy_number"
                      @change="(e) => buyNumberChange(e)"
                      bgColor="#E8EDF5"
                      color="#9695A3"
                      inputWidth="25"
                      buttonSize="25"
                      iconStyle="color: #9695A3"></u-number-box>
                  </view>
                </view>
              </view>
            </view>

            <view class="modal-foot">
              <view class="btns flex-center" v-if="!is_miaosha">
                <view class="btn flex-center btn-cart" @click="doAddCart()">
                  加入购物车
                </view>
                <view class="btn flex-center btn-buy" @click="doBuy()">
                  立即购买
                </view>
              </view>

              <view class="btns flex-center" v-if="is_miaosha">
                <view
                  class="btn flex-center btn-buy btn-flash"
                  @click="doBuy()">
                  立即抢购
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </u-popup>
  </view>
</template>

<script>
export default {
  props: {},
  data() {
    return {
      sku_mode: "", //无规格 单规格 多规格
      guige_list: [], //所有规格
      guige_select: {}, //已选规格
      sku_sections: [], //sku分组 多规格
      sku_flat_list: [], //规格sku列表
      // inventorys: [],
      //
      show_pop: false,
      is_miaosha: false, //是否秒杀商品
      info: {
        banners: [],
      },
      //
      //
      //
      //

      banners: [],
      guigeList: [],
      buyNumber: 1,
      guigeSelect: {},
      allowRequestApi: true, //是否允许请求接口  针对上报 提交 保存类限制次数

      //多规格数据 多规格数据
      all_guige: [],

      user_select_attrs: [],
      select_specifications: {},
      list_specifications: [],
    };
  },
  computed: {
    guige_poster() {
      let poster = this.guige_select.thumb || this.info.thumb || "";
      // if (this.sku_mode == '无规格') {
      // 	poster = this.info.thumb
      // } else {
      // 	// this.guige_select.thumb;
      // }
      return poster;
    },

    max_buy_number() {
      let max = 0;
      if (this.guige_select.inventoryId) {
        max = this.guige_select.kucun;
      }
      return max;
    },
  },
  watch: {},
  methods: {
    init(info) {
      this.$log("选择规格 init info", info);
      this.buyNumber = 1;
      this.info = info;
      this.is_miaosha = info.is_miaosha;
      this.sku_format(info); //处理商品规格信息
      this.show_pop = true;
    },

    //处理商品规格信息
    sku_format(data) {
      /**
       * 规格处理逻辑
       * 无规格 1
       *
       * 有规格
       *   单一规格 1
       *   多组规格
       */

      // inventorys = [{
      // 	image: "",
      // 	inventoryId: 24,
      // 	isSelected: 0,
      // 	keyVals: "黑,大",
      // 	kucun: 1000,
      // 	priceMarket: "200.00",
      // 	priceSale: "100.00",
      // 	priceTuan: "150.00",
      // 	sn: "编码",
      // }]

      let inventorys = data.inventorys || [];
      let skuLists = data.skuLists || [];

      //
      let sku_mode = "";
      let guige_list = [];
      let sku_sections = [];
      let sku_flat_list = [];

      //
      if (!skuLists.length) {
        sku_mode = "无规格";
      } else if (skuLists.length == 1) {
        sku_mode = "单规格";
      } else if (inventorys.length) {
        sku_mode = "多规格";
      }

      if (sku_mode == "无规格") {
        if (!inventorys.length) {
          inventorys = [
            {
              image: data.thumb,
              inventoryId: data.inventoryId,
              isSelected: 1,
              keyIds: data.inventoryId + "",
              keyVals: data.keyVals,
              kucun: data.kucun,
              priceMarket: data.priceMarket,
              priceSale: data.priceSale,
              priceTuan: data.priceTuan,
              sn: data.sn,
            },
          ];
        }

        guige_list = inventorys;
        if (guige_list[0].kucun > 0) {
          this.guige_select = guige_list[0];
        }
      } else if (sku_mode == "单规格" || sku_mode == "多规格") {
        guige_list = inventorys;
        sku_sections = skuLists;
        sku_sections.forEach((v1) => {
          v1.child.forEach((v2) => {
            v2.is_selected = false;
            v2.is_allow_select = true;
            sku_flat_list.push(v2);
          });
        });
      }

      guige_list.forEach((v) => {
        let { keyIds, keyVals } = v;
        let sku_map = {};
        let id_arr = keyIds.split("-").map((v) => parseInt(v));
        let sku_id_arr = id_arr.sort((a, b) => a - b);
        v.cus_sku_ids = sku_id_arr.join("-"); //当前规格的sku组合

        let sku_id_list = keyIds.split("-").map((v) => parseInt(v));
        let sku_value_list = keyVals.split(",");

        sku_id_list.forEach((id, index) => {
          sku_map[id] = sku_value_list[index];
        });
        v.sku_map = sku_map;
        v.sku_id_list = sku_id_list;
        v.sku_value_list = sku_value_list;
      });

      this.sku_mode = sku_mode;
      this.guige_list = guige_list;
      this.sku_sections = sku_sections;
      this.sku_flat_list = sku_flat_list;
      // this.inventorys = inventorys;

      this.$log("所有规格 guige_list", guige_list);
    },

    do_toggle_wuguige(item) {
      this.guige_select = item;
    },

    //商品sku 属性选择
    do_toggle_sku(sku_item, item_index, sku_group, group_index) {
      this.$log("切换sku", sku_item);

      if (!sku_item.is_allow_select) {
        //无库存
        return;
      }

      if (sku_item.is_selected) {
        //已选- 取消勾选
        return;
        // sku_item.is_selected = false;
        // sku_group.is_selected = false
      } else {
        //未选-
        let is_allow_select_this = true; //是否允许勾选当前sku 库存不允许勾选
        if (is_allow_select_this) {
          let other_select_sku_item = sku_group.child.find(
            (v) => v.is_selected
          ); //其他已选规格
          if (other_select_sku_item) {
            other_select_sku_item.is_selected = false;
          }
          sku_item.is_selected = true;
        }
      }

      if (sku_item.is_selected) {
        sku_group.is_selected = true;
      }

      this.update_sku_allow_select_status();
      this.set_guige_select_by_select_sku();
    },

    //更新 sku 是否允许勾选状态
    update_sku_allow_select_status() {
      this.sku_flat_list.forEach((v) => {
        v.is_allow_select = true;
      });
      //已选sku
      //已选sku对应的规格数据
      //
      let sku_select_items = this.sku_flat_list.filter((v) => v.is_selected);
      let sku_select_map = {};
      sku_select_items.forEach((v) => {
        sku_select_map[v.id] = v.title;
      });
      let has_kucun_guige_list = this.guige_list.filter((v) => v.kucun > 0);

      //sku是否可选设置

      this.sku_flat_list.forEach((sku) => {
        let need_manzu_sku_items = sku_select_items.filter(
          (v) => v.parentId != sku.parentId
        );
        let need_manzu_sku_value = {
          [sku.id]: sku.title,
        };
        need_manzu_sku_items.forEach((v) => {
          need_manzu_sku_value[v.id] = v.title;
        });
        //当前sku 是否可选 需要判断  当前sku与所有已选sku的组合在规格列表中是否有库存

        let this_sku_has_kucun = has_kucun_guige_list.some(function (guige) {
          let has_every_sku = true; //检测规格是否包含所有sku组合
          let sku_map = guige.sku_map;

          for (var sku_id in need_manzu_sku_value) {
            if (need_manzu_sku_value[sku_id] != sku_map[sku_id]) {
              has_every_sku = false;
            }
          }
          return has_every_sku;
        });

        if (this_sku_has_kucun) {
          sku.is_allow_select = true;
        } else {
          sku.is_allow_select = false;
        }
      });

      this.$log("有库存的产品规格 has_kucun_guige_list", has_kucun_guige_list);
      this.$log("所有sku更新状态  sku_flat_list", this.sku_flat_list);
    },

    //通过已勾选的sku 确认规格项目
    set_guige_select_by_select_sku() {
      let guige_select = {};

      let sku_select_items = this.sku_flat_list.filter((v) => v.is_selected);
      if (sku_select_items.length != this.sku_sections.length) {
        guige_select = {};
      } else {
        let sku_id_arr = sku_select_items
          .map((v) => v.id)
          .sort((a, b) => parseInt(a) - parseInt(b));
        let cus_sku_ids = sku_id_arr.join("-"); //当前规格的sku组合

        guige_select =
          this.guige_list.find((v) => v.cus_sku_ids == cus_sku_ids) || {};
      }

      this.guige_select = guige_select;

      this.$log("已选规格", this.guige_select);

      // if (this.guige_type == '单规格') {
      // 	this.$emit('confirm', {
      // 		type: '单规格',
      // 		guige: this.guigeSelect,
      // 		buyNumber: this.buyNumber
      // 	})
      // } else if (this.guige_type == '多规格') {
      // 	this.$emit('confirm', {
      // 		type: '多规格',
      // 		guige: this.select_specifications,
      // 		buyNumber: this.buyNumber
      // 	})
      // }
    },

    // 立即购买
    doBuy() {
      if (!this.mix_checkLogin()) {
        return;
      }
      if (!this.guige_select.inventoryId) {
        this.$alert("请选择规格");
        return;
      }
      if (this.buyNumber > this.guige_select.kucun) {
        this.$alert("商品库存不足");
        return;
      }
      this.doBuyFn();
    },

    // 立即购买
    doBuyFn() {
      let info = this.info;
      let guige = this.guige_select || {};

      let items_format = [
        {
          title: info.title,
          image: guige.image || info.thumb,
          inventoryId: guige.inventoryId,
          productId: this.info.productId,
          keyVals: guige.keyVals,
          num: this.buyNumber,
          priceSale: guige.priceSale,
          priceMarket: guige.priceMarket,
        },
      ];
      this.$log("待下单产品信息", items_format);
      this.$store.commit(
        "set_cache_payment_products",
        JSON.stringify(items_format)
      );
      // return

      let seckillInfo = this.info.seckillInfo || {};
      this.toRoute({
        path: "/order-submit",
        query: {
          from: "product-detail",
          is_miaosha: this.is_miaosha ? 1 : 0,
          cuxiaoId: seckillInfo.id || "",
        },
      });

      this.show_pop = false;
    },

    // 规格处理

    handleClose() {
      this.show_pop = false;
    },
    handleOpen() {},

    doClose() {
      this.show_pop = false;
    },

    doMinus() {
      if (this.buyNumber > 1) {
        this.buyNumber--;
      }
    },
    doPlus() {
      if (!this.guige_select.inventoryId) {
        this.$alert("请选择商品规格");
        return;
      }
      let current_kucun = this.guige_select.kucun;

      if (this.buyNumber + 1 > current_kucun) {
        this.$alert("商品库存不足");
      } else {
        this.buyNumber++;
      }
    },

    buyNumberChange(e, item) {
      console.log("e 当前值为: ", e);
    },

    // 商品加入购物车
    doAddCart() {
      console.log("商品加入购物车");
      this.$log("this.guigeSelect", this.guigeSelect);
      this.$log("this.guigeList", this.guigeList);

      if (!this.mix_checkLogin()) {
        return;
      }

      if (!this.guige_select.inventoryId) {
        this.$alert("请选择规格");
        return;
      }
      if (this.buyNumber > this.guige_select.kucun) {
        this.$alert("商品库存不足");
        return;
      }

      //
      uni.$u.throttle(this.doAddCartFn, 1000, true);
    },

    doAddCartFn() {
      this.$api({
        url: "/service.php",
        method: "post",
        data: {
          action: "gouwuche_add",
          inventoryId: this.guige_select.inventoryId,
          num: this.buyNumber,
        },
      }).then((res) => {
        this.$alert(res);
        if (res.code == 200) {
          this.$store.commit("set_vuex_cart_number", res.data.count);
          this.show_pop = false;
          this.$emit("confirm");
        }
      });
    },

    doPreviewPoster() {
      uni.previewImage({
        urls: [this.guige_poster],
      });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .u-number-box__minus {
  width: 25px;
}

::v-deep .u-number-box__plus {
  width: 25px;
}

.pop-product-choose-guige {
  position: relative;
  z-index: 999;
}

.pop-ctx {
  width: 660rpx;
  width: 100%;
  position: relative;
  text-align: left;
  padding-bottom: 0;

  .info-modal-inner {
    border-radius: 16rpx;
    overflow: hidden;
    width: 100%;
    padding: 0 0;
    padding-bottom: 20rpx;
    padding-bottom: 32rpx;
    min-height: 600rpx;
    background: #ffffff;
  }
}

.close-box {
  width: 28rpx;
  height: 28rpx;

  image {
    width: 28rpx;
    height: 28rpx;
  }
}
.modal-head {
  padding: 40upx 32upx 0;
  margin-bottom: 10upx;
}
.top-box {
  display: flex;
  padding-bottom: 40upx;
  border-bottom: 2rpx solid #f3f4f8;
  .poster-box {
    width: 168rpx;
    height: 168rpx;

    image {
      width: 168rpx;
      height: 168rpx;
    }
  }

  .info-box {
    flex: 1;
    padding-left: 24rpx;

    .title {
      padding-right: 86rpx;
      font-weight: bold;
      font-size: 28rpx;
      color: #000000;
    }

    .remark {
      margin-top: 6rpx;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 20rpx;
      color: #838b9e;
    }

    .tags {
      margin-top: 16rpx;
      flex-wrap: wrap;

      .tag {
        margin-right: 20rpx;

        height: 36rpx;
        background: #f5f5f5;
        border-radius: 4rpx 4rpx 4rpx 4rpx;
        padding: 0 10rpx;

        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 20rpx;
        color: #7d7d7d;
      }
    }

    .price-box {
      margin-top: 48rpx;

      .price {
        .price-val {
          font-weight: bold;
          font-size: 32rpx;
          color: #e23410;
        }
      }

      .price-line {
        margin-left: 20rpx;
        overflow: hidden;
        text-decoration: line-through;
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 20rpx;
        color: #7d7d7d;
      }

      .tip {
        margin-left: 20rpx;
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 20rpx;
        color: #f54242;
      }
    }
  }
}

.modal-ctx {
  width: 100%;
  background-color: #fff;
  padding: 24rpx 32rpx;

  .main-title {
    margin-bottom: 30rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: 800;
    font-size: 28rpx;
    color: #222222;
  }

  .number-box {
    position: relative;
    right: -20rpx;

    .box-act {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 80rpx;
      height: 80rpx;

      image {
        width: 40rpx;
        height: 40rpx;
      }
    }

    .num {
      text-align: center;
      width: fit-content;
      height: 40rpx;
      line-height: 40rpx;
    }
  }

  .guige-list {
    margin-bottom: 27rpx;
    flex-wrap: wrap;

    .guige-item {
      margin-right: 18rpx;
      margin-bottom: 16rpx;
      padding: 0 110rpx;
      min-width: 150rpx;
      height: 64rpx;
      background: #f6fafd;
      border-radius: 50rpx 50rpx 50rpx 50rpx;
      font-weight: 400;
      font-size: 28rpx;
      color: #000000;

      &.selected {
        background: #f49c0d;
        color: #ffffff;
      }

      &.nokucun {
        background: #eeeeee;
        color: #aaaaaa;
      }
    }
  }

  .sku-list {
    margin-bottom: 27rpx;
    flex-wrap: wrap;

    .sku-item {
      margin-right: 18rpx;
      margin-bottom: 16rpx;
      padding: 0 110rpx;
      min-width: 150rpx;
      height: 64rpx;
      background: #f6fafd;
      border-radius: 50rpx 50rpx 50rpx 50rpx;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 28rpx;
      color: #000000;

      &.selected {
        background: #f49c0d;
        color: #ffffff;
      }

      &.nokucun {
        background: #eee;
        color: #aaaaaa;
      }
    }
  }
}

.modal-foot {
  margin-top: 30rpx;
  padding: 0 32rpx;

  .btn {
    flex: 1;
    font-family: PingFang SC, PingFang SC;
    font-weight: bold;
    font-size: 28rpx;
    color: #ffffff;

    &.btn-cart {
      height: 80rpx;
      border-radius: 40rpx 0rpx 0rpx 40rpx;
      background: #f40d0d;
    }

    &.btn-buy {
      height: 80rpx;
      background: #f49c0d;
      border-radius: 0rpx 40rpx 40rpx 0rpx;
    }

    &.btn-flash {
      border-radius: 40rpx;
    }

    &.btn-disabled {
      background: #dddddd;
    }

    &[disabled] {
      background: #dddddd;
    }
  }
}
.choose-scroll {
  max-height: 900rpx;
}
</style>
